package com.itheima.service.store.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.store.CourseDao;
import com.itheima.domain.store.Course;
import com.itheima.factory.MapperFactory;
import com.itheima.service.store.CourseService;
import com.itheima.utils.UUIDUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;

public class CourseServiceImpl implements CourseService {
    @Override
    public PageInfo<Course> queryPage(Integer pageNum, Integer pageSize) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CourseDao courseDao = sqlSession.getMapper(CourseDao.class);

        PageHelper.startPage(pageNum,pageSize);
        List<Course> list = courseDao.findAll();
        PageInfo<Course> pageInfo = new PageInfo<>(list);

        sqlSession.close();
        return pageInfo;
    }

    @Override
    public List<Course> findAll() throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CourseDao courseDao = sqlSession.getMapper(CourseDao.class);

        List<Course> list = courseDao.findAll();

        sqlSession.close();
        return list;
    }

    @Override
    public Course findById(String id) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CourseDao courseDao = sqlSession.getMapper(CourseDao.class);

        Course course = courseDao.findById(id);

        sqlSession.close();
        return course;
    }

    @Override
    public void save(Course course) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CourseDao courseDao = sqlSession.getMapper(CourseDao.class);

        course.setId(UUIDUtil.getSimpleUUID());
        course.setCreateTime(new Date());
        courseDao.save(course);

        sqlSession.commit();
        sqlSession.close();

    }

    @Override
    public void update(Course course) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CourseDao courseDao = sqlSession.getMapper(CourseDao.class);

        courseDao.update(course);

        sqlSession.commit();
        sqlSession.close();

    }

    @Override
    public void deleteById(String... ids) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CourseDao courseDao = sqlSession.getMapper(CourseDao.class);

        for (String id : ids) {
            courseDao.deleteById(id);
        }

        sqlSession.commit();
        sqlSession.close();
    }
}
